/*
 * @Author: qiuz
 * @Date: 2018-04-13 16:02:14
 * */

import { isObject, isArray } from '../is-type';

/**
 * @function
 * @description 对象的深拷贝覆盖
 * @param {object} target
 * @param {object} source
 * @example
 * assignDeep({a: 1, b: 2, c:[{c1: 1, c2: 2}]}, {a: 2, b: [1,2,3], c: [{c3: 3}]})
 * // return {a:2, b: [1,2,3], c: [{c1:1, c2: 2, c3: 3}]}
 *
 * @returns {object}
 */
function assignDeep(target, source) {
	Object.keys(source).forEach(key => {
		if (isObject(source[key]) && isObject(target[key])) {
			assignDeep(target[key], source[key]);
		} else if (isArray(source[key]) && isArray(target[key])) {
			source[key].forEach((arr, index) => {
				isObject(arr) && isObject(target[key][index])
					? assignDeep(target[key][index], arr)
					: target[key][index] = arr;
			});
		} else if (isObject(source[key]) && !target[key]) {
			target[key] = {};
			assignDeep(target[key], source[key]);
		} else if (isArray(source[key]) && !target[key]) {
			target[key] = [];
			assignDeep(target[key], source[key]);
		} else {
			target[key] = source[key];
		}
	});
	return target;
}

export default assignDeep
;
